Reverse bits

Time: O(LogN)=O(32); Space: O(1); easy

Example:

Input: 43261596

Output: 964176192

Explanation:

  • 43261596 represented in binary as 00000010100101000001111010011100

  • 964176192 represented in binary as 00111001011110000010100101000000

Follow up:

  • If this function is called many times, how would you optimize it?

[1]:
class Solution1(object):
    def reverseBits(self, num) -> int:
        """
        :type num: int
        :rtype: int
        """
        result = 0
        for i in range(32):
            result <<= 1
            result |= num & 1
            num >>= 1
        return result
[2]:
s = Solution1()
num = 43261596
assert s.reverseBits(num) == 964176192
[3]:
class Solution2(object):
    def reverseBits(self, num) -> int:
        """
        :type num: int
        :rtype: int
        """
        string = bin(num)
        if '-' in string:
            string = string[:3] + string[3:].zfill(32)[::-1]
        else:
            string = string[:2] + string[2:].zfill(32)[::-1]
        return int(string, 2)
[4]:
s = Solution2()
num = 43261596
assert s.reverseBits(num) == 964176192